<template>
  <div class="main-box">
    <TreeFilter
      class="tf"
      label="name"
      title="菜品分类(单选)"
      :data="treeFilterData"
      :default-value="initParam.foodCategoryId"
      @change="changeTreeFilter"
      @change-share="changeShare"
    />
    <div class="table-box">
      <ProTable
        ref="proTable"
        title="菜品列表"
        row-key="id"
        border
        :indent="20"
        :columns="columns"
        :request-api="getGoodsList"
        :request-auto="false"
        :init-param="initParam"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
        :span-method="objectSpanMethod"
        :merger-fields="['foodTypeName']"
        :is-span-method="true"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="toCreate(0)"> 新增菜品</el-button>
        </template>
        <!-- 表格操作 -->
        <template #ingredient="scope">
          <el-button
            v-if="scope.row.type === 1 && scope.row.isGoods !== 2"
            v-auth="'foodSet'"
            type="primary"
            link
            :icon="EditPen"
            @click.stop="openIngredientDialog(scope.row)"
          >
            编辑原料
          </el-button>
          <div v-else>--</div>
        </template>
        <template #id="scope">
          <el-text>{{ scope.row.name }}</el-text>
        </template>
        <template #operation="scope">
          <el-button v-auth="'edit'" type="primary" link :icon="EditPen" @click.stop="toCreate(scope.row.id, scope.row.isShare)">
            编辑
          </el-button>
          <el-button
            v-auth="'delete'"
            v-if="!scope.row.isShare"
            type="primary"
            link
            :icon="Delete"
            @click.stop="deleteAccount(scope.row)"
          >
            删除
          </el-button>
        </template>
      </ProTable>
    </div>
    <IngredientDialog ref="ingredientDialogRef" />
  </div>
</template>

<script setup lang="tsx" name="GoodsList">
import { onMounted, reactive, ref, onBeforeUpdate } from "vue";
import { useRouter, useRoute } from "vue-router";
import { Goods, Product } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import IngredientDialog from "@/views/goods/components/IngredientDialog.vue";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { CirclePlus, Delete, EditPen } from "@element-plus/icons-vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { getFoodCategoryList, getGoodsList, deleteFood, getFoodSet, editFoodSet } from "@/api/modules/goods";
import { getDepartMentList } from "@/api/modules/operation";
// import { ElMessage } from "element-plus";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();
// const batchingTableData = ref<Product.ResProductList>([]);
const route = useRoute();
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ foodCategoryId: 0 });

// 获取 treeFilter 数据
// 当 proTable 的 requestAuto 属性为 false，不会自动请求表格数据，等待 treeFilter 数据回来之后，更改 initParam.foodCategoryId 的值，才会触发请求 proTable 数据
const treeFilterData = ref<any>([]);
// const FoodSpecId = ref(0);
// const FoodId = ref(0);
const getTreeFilter = async (isBack?: boolean) => {
  const { data } = await getFoodCategoryList({ pageNum: 1, pageSize: 9999, listType: 1 });
  treeFilterData.value = data.list;
  if (route.query?.categoryId) {
    initParam.foodCategoryId = Number(route.query?.categoryId) as number;
  }
  if (!isBack) {
    initParam.foodCategoryId = treeFilterData.value[0].id;
    isShare.value = treeFilterData.value[0].isShare ? treeFilterData.value[0].isShare : 0;
  }
};

// 判断是不是总店数据
const isShare = ref(0);
const changeShare = (val: number) => {
  isShare.value = val;
  console.log(val, "lailailia");
};

// 树形筛选切换
const changeTreeFilter = (val: any) => {
  // batchingTableData.value = [];
  proTable.value!.pageable.pageNum = 1;
  proTable.value?.resetTableData();
  initParam.foodCategoryId = val;
  // FoodSpecId.value = 0;
};
const router = useRouter();
// 跳转详情页面
const toCreate = (id?: number, share?: number) => {
  if (id !== 0) {
    router.push({
      path: "/goods/goods-add-copy",
      query: {
        id: id,
        type: share ? 1 : 0
      }
    });
  } else {
    router.push({
      path: `/goods/goods-add-copy`,
      query: {
        foodCategoryId: isShare.value ? 0 : initParam.foodCategoryId
      }
    });
  }
};

// 表格配置项
const columns: ColumnProps<Goods.ResGoodsList>[] = [
  { sortable: true, prop: "id", label: "菜品名称", align: "left", minWidth: 160, search: { el: "input", key: "name" } },
  { sortable: true, prop: "foodTypeName", label: "菜品分类", minWidth: 120, align: "left" },
  {
    sortable: true,
    prop: "type",
    label: "菜品类型",
    minWidth: 120,
    align: "left",
    enum: [
      { label: "全部菜品", value: 0 },
      { label: "普通菜", value: 1 },
      { label: "套菜", value: 2 },
      { label: "线下临时菜", value: 3 },
      { label: "打包盒", value: 4 }
    ],
    search: { el: "select" }
  },
  {
    sortable: true,
    prop: "departId",
    label: "出品部门",
    minWidth: 120,
    isShow: false,
    align: "left",
    enum: () => getDepartMentList({ pageNum: 1, pageSize: 9999 }),
    search: { el: "select" },
    fieldNames: { label: "name", value: "id" }
  },
  { sortable: true, prop: "foodSpecName", label: "规格名称", minWidth: 100, align: "left" },
  { sortable: true, prop: "posPrice", label: "销售价格", align: "left", minWidth: 100 },
  { sortable: true, prop: "sort", label: "排序", width: 80 },
  {
    sortable: true,
    prop: "sellStatus",
    label: "菜品状态",
    enum: [
      { label: "在售", value: 1 },
      { label: "停售", value: 2 },
      { label: "尚未起售", value: 0 }
    ],
    minWidth: 90,
    search: { el: "tree-select" },
    fieldNames: { label: "label", value: "value" }
  },
  { prop: "operation", label: "操作", width: 150 },
  { prop: "ingredient", label: "原料配比", width: 110 }
];

// 删除菜品
const deleteAccount = async (params: Goods.ResGoodsList) => {
  await useHandleData(deleteFood, { id: params.id }, `删除【${params.name}】菜品`);
  proTable.value?.getTableList();
};

// 合并行
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  if (row.mergeCell.includes(column.property)) {
    const rowspan = row[`rowspan_${column.property}`];
    if (rowspan) {
      // console.log(row[`rowspan_${column.property}`]);

      return { rowspan: rowspan, colspan: 1 };
    } else {
      return { rowspan: 0, colspan: 0 };
    }
  }
};

const ingredientDialogRef = ref<InstanceType<typeof IngredientDialog> | null>(null);
const openIngredientDialog = async (row: Partial<Product.ResProductList> = {}) => {
  const { data } = await getFoodSet({ id: row.foodSpecId });
  // console.log(111, data);

  const params = {
    title: "原料配比",
    goodsInfo: row,
    tableData: data.foodSetList,
    isView: false,
    api: editFoodSet
  };
  ingredientDialogRef.value?.acceptParams(params);
};

onMounted(() => {
  getTreeFilter(route.query?.categoryId ? true : false);
});

onBeforeUpdate(() => {
  if (route.query?.upList) {
    // proTable.value?.getTableList();
    // console.log(111);
  }
});

// // 拖拽表格
// const dargSort = (e: { newIndex?: number; oldIndex?: number }) => {
//   console.log(e);
// };
</script>
<style lang="scss" scoped>
.good-table {
  display: flex;
  flex: 1;
  flex-direction: column;
  width: calc(100% - 670px);
  width: 100%;
  height: 100%;
}
.tf {
  flex-shrink: 0;
}
.batching-table {
  flex-shrink: 0;
  width: 450px;
}
</style>
